package r2dbc;

import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@SpringBootApplication
@RestController
public class R2dbcApp {
    public static void main(String[] args) {
        SpringApplication.run(R2dbcApp.class,args);
    }
    @Bean
    ConnectionFactory connectionFactory(){
        return ConnectionFactories.get("r2dbc:mysql://root:123@localhost:3306/my_db");
    }
    @GetMapping("/accounts")
    public Flux<Account> findAllAccounts(){
        ConnectionFactory factory = connectionFactory();
        return Flux.from(factory.create())
                .flatMap(connection -> connection.createStatement("select * from accounts").execute())
                .flatMap(result -> result.map((row,meta)->new Account(row.get("id",Integer.class),row.get("name",String.class))));
    }

}
